package initialize

import (
	"context"
	"fmt"
	"github.com/olivere/elastic/v7"
	"log"
	"mxshop_srvs/goods_srv/global"
	"mxshop_srvs/goods_srv/model"
	"os"
)

func InitEs() {
	//初始化连接
	esInfo := global.ServerConfig.EsInfo
	info := fmt.Sprintf("http://%s:%d", esInfo.Host, esInfo.Port)
	//这里必须将sniff设置为false,因为使用 olivere/elastic连接es时,发现连接地址明明输入的时候是外网地址,
	//但是连接时会自动转换成内网地址或者docker中的ip地址,导致服务连不上
	logger := log.New(os.Stdout, "mxshop:", log.LstdFlags) //设置跟踪日志
	client, err := elastic.NewClient(elastic.SetURL(info), elastic.SetSniff(false), elastic.SetTraceLog(logger))
	if err != nil {
		panic(err)
	}
	global.EsClient = client
	//新建 mappings 和 index
	var egoods model.EsGoods
	
	exists, err := global.EsClient.IndexExists(egoods.GetIndexName()).Do(context.Background())
	if err != nil {
		panic(err)
	}
	if !exists {
		_, err := global.EsClient.CreateIndex(egoods.GetIndexName()).Body(egoods.GetMapping()).Do(context.Background())
		if err != nil {
			panic(err)
		}
	}
}
